#ifndef TRIETREE_H
#define TRIETREE_H

#include <unistd.h>
#include <stdint.h>
#include <vector>
#include <map>
#include <iostream>

class TrieTree {
public:
    void addNode(std::vector<uint32_t>& vWord) {
        if (vWord.empty()) return;

        TrieNode* pNode = &m_stRoot;
        for (auto& iWrod : vWord) {
            pNode = &(pNode->mNodes[iWrod]);
        }
        pNode->bTerminal = true;
    }
    bool find(const uint32_t* pBegin, const uint32_t* pEnd, uint32_t& iLen) {
        if (nullptr == pBegin || nullptr == pEnd || pBegin >= pEnd) {
            return false;
        }

        bool bFind = false;
        const TrieNode* pNode = &m_stRoot;
        for (const uint32_t* p = pBegin; p < pEnd; ++p) {
            auto it = pNode->mNodes.find(*p);
            if (it == pNode->mNodes.end()) {
                break;
            }

            pNode = &it->second;
            if (pNode->bTerminal) {
                bFind = true;
                iLen = p - pBegin + 1;
            }
        }

        return bFind;
    }

private:
    struct TrieNode {
        bool bTerminal = false;
        std::map<uint32_t, TrieNode> mNodes;
    };

    TrieNode m_stRoot;
};

#endif // TRIETREE_H
